package com.xc.file.service.impl;

import com.xc.file.config.Constants;
import com.xc.file.enums.FailCode;
import com.xc.file.info.FileTypeInfo;
import com.xc.file.info.FolderInfo;
import com.xc.file.service.DownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: 下载服务实现</p>
 * <P>创建人:小程 </p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/11/20</p>
 *
 * @version v1.0
 */
@Service
public class DownloadServiceImpl implements DownloadService {
    @Autowired
    private Constants constants;

    @Override
    public void downloadFile(String fileName, String hashCode, String range, HttpServletResponse response, int open) {
        String filePath = getFilePath(hashCode);
        if (filePath == null) {
            throw FailCode.DOWNLOAD_FILE_NOT_EXIST.getOperateException();
        }
        //下载
        download(response, new File(filePath), range, fileName, open);
    }

    /**
     * 获取文件路径
     *
     * @param hashCode 文件hash值
     * @return 如果存在多个文件全部返回
     */
    private String getFilePath(String hashCode) {
        List<FolderInfo> folderPath = constants.getFolderPaths();
        String filePath = null;
        for (FolderInfo folderInfo : folderPath) {
            String path = folderInfo.getPath() + File.separator + hashCode + constants.getSuffix();
            File file = new File(path);
            if (file.exists()) {
                filePath = path;
            }
        }
        return filePath;
    }

    /**
     * 下载文件及断点续传
     *
     * @param response Response
     * @param file     下载文件
     * @param range    Header参数
     * @param open     是否直接打开
     */
    private void download(HttpServletResponse response, File file, String range, String fileName, int open) {
        // 清空response
        response.reset();
        String rangBytes;
        long startIndex = 0; //下载开始的字节数
        long stopIndex = 0; //下载结束的字节数
        long fileLength; //文件的字节数
        //配置header
        if (range != null && range.trim().length() > 0 && !"null".equals(range)) {
            rangBytes = range.replaceAll("bytes=", "");
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            // 判断最后是不是 -
            if (rangBytes.endsWith("-")) {
                //结尾是-
                startIndex = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                fileLength = file.length() - startIndex;
                String contentRange = "bytes " + startIndex + "-" + (file.length() - 1) + "/" + file.length();
                response.setHeader("Content-Range", contentRange);
            } else { //结尾不是-
                startIndex = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                stopIndex = Long.parseLong(rangBytes.substring(rangBytes.indexOf("-") + 1));
                fileLength = (stopIndex + 1) - startIndex;
                String contentRange = range.replace("=", " ") + "/" + file.length();
                response.setHeader("Content-Range", contentRange);
            }
        } else {
            fileLength = file.length();
            String contentRange = "bytes " + "0-" + (fileLength - 1) + "/" + fileLength;
            response.setHeader("Content-Range", contentRange);
        }
        response.setHeader("Content-Length", Long.toString(fileLength));
        //返回文件
        RandomAccessFile loOutput = null;
        OutputStream out = null;
        try {
            //文件是否可以直接打开
            if (open == 0) {
                response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "utf-8"));
            } else {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            }
            String suffix = "";
            if (fileName.lastIndexOf(".") != -1) {
                suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            }
            FileTypeInfo fileType = null;
            for (FileTypeInfo fileTypeInfo : constants.getFileTypes()) {
                if (suffix.equals(fileTypeInfo.getSuffix())) {
                    fileType = fileTypeInfo;
                }
            }
            if (fileType != null) {
                response.setContentType(fileType.getType());
            } else {
                response.setContentType("application/octet-stream");
            }
            //配置header
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Access-Control-Allow-Origin", "*");
            //返回的输出流
            out = response.getOutputStream();
            loOutput = new RandomAccessFile(file, "r");
            loOutput.seek(startIndex);
            //创建缓存大小
            byte[] buffer = new byte[constants.getCacheSize()]; // 1KB
            int n;
            long readLength = 0;
            //判断是否指定结束位置
            if (stopIndex != 0) {
                while (readLength <= fileLength - buffer.length) {
                    n = loOutput.read(buffer);
                    readLength += n;
                    out.write(buffer, 0, n);
                }
                if (readLength <= fileLength) {
                    n = loOutput.read(buffer, 0, (int) (fileLength - readLength));
                    out.write(buffer, 0, n);
                }
            } else {
                while ((n = loOutput.read(buffer)) != -1) {
                    out.write(buffer, 0, n);
                }
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (loOutput != null) {
                try {
                    loOutput.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
